package per.ethan.cloud.generator.entity;

import per.ethan.cloud.generator.utils.DBUtil;
import per.ethan.cloud.generator.utils.StringUtil;
import lombok.Data;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Ethan
 * @date 2020/03/31 13:54
 */
@Data
public class Property {

    /**
     * JAVA中的字段类型
     */
    private String javaType;

    /**
     * 类的全名称
     */
    private String fullJavaType;

    /**
     * 属性名称
     */
    private String propertyName;

    /**
     * 字段名称
     */
    private String fieldName;

    /**
     * 字段类型
     */
    private String fieldType;

    /**
     * 字段长度
     */
    private String length;

    /**
     * 字段的注释信息
     */
    private String comment;

    /**
     * 验证属性: 是否允许非空
     */
    private boolean notNull;

    /**
     * 验证属性: 验证的正则表达式
     */
    private String regex;

    /**
     * 验证属性: 验证不通过返回的提示信息
     */
    private String tip;

    private boolean validationField = false;

    /**
     * 是否是父类的属性
     */
    private boolean parentProperty = false;

    public void init() {
        this.propertyName = StringUtil.toUpperCaseAndRemoveUnderLine(fieldName);
        this.javaType = DBUtil.dbType2JavaType(fieldType.toLowerCase());
        this.fullJavaType = DBUtil.dbType2FullJavaType(fieldType.toLowerCase());

        String regex = "(.*)\\|([^`]*?)(`([^`]*?))?(`([^`]*?))?";
        /*String str = "订单ID|true,aa,bb";*/

        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(comment);

        if (matcher.matches()) {
            String comment = matcher.group(1);
            Boolean notNull = Boolean.parseBoolean(matcher.group(2));
            String regexStr = matcher.group(4);
            String tip = matcher.group(6);

            this.comment = comment;
            this.notNull = notNull;
            this.regex = regexStr == null ? "" : regexStr;
            this.tip = tip == null ? "" : tip;
            this.validationField = true;
        }
    }

}
